package com.pony.iphone.config;

import com.theokanning.openai.service.OpenAiService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class DeepSeekConfig {

    @Value("${spring.ai.openai.api-key}")
    private String apiKey;
    
    @Value("${spring.ai.openai.base-url}")
    private String baseUrl;
    
    @Value("${app.ai.timeout:300000}")
    private long timeout;

    @Bean
    @Primary
    public OpenAiService openAiService() {
        try {
            log.info("🚀 初始化DeepSeek服务");
            log.info("📡 API端点: {}", baseUrl);
            log.info("⏱️ 超时时间: {}ms ({}分钟)", timeout, timeout / 60000);
            log.info("🔑 API Key: {}", apiKey.substring(0, 8) + "***"); // 只显示前8位

            // 创建自定义的OkHttpClient
            OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(Duration.ofMinutes(5)) // 连接超时5分钟
                .readTimeout(Duration.ofMinutes(5))    // 读取超时5分钟
                .writeTimeout(Duration.ofMinutes(5))   // 写入超时5分钟
                .callTimeout(Duration.ofMinutes(10))   // 整个调用超时10分钟
                .build();

            // 使用反射设置自定义的httpClient（因为OpenAiService构造函数有限制）
            OpenAiService service = new OpenAiService(apiKey, Duration.ofMinutes(5));
            
            // 通过反射设置自定义的httpClient
            try {
                java.lang.reflect.Field clientField = service.getClass().getDeclaredField("client");
                clientField.setAccessible(true);
                clientField.set(service, httpClient);
                
                log.info("✅ 自定义HttpClient设置成功");
            } catch (Exception reflectionException) {
                log.warn("⚠️ 无法设置自定义HttpClient，使用默认配置: {}", reflectionException.getMessage());
            }
            
            log.info("✅ DeepSeek服务初始化成功");
            return service;

        } catch (Exception e) {
            log.error("❌ DeepSeek服务初始化失败", e);
            throw new RuntimeException("DeepSeek服务初始化失败", e);
        }
    }
}